package com.rockcent.wechat.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.rockcent.common.common.JsonResult;
import com.rockcent.common.common.PageResult;
import com.rockcent.common.common.RestDoing;
import com.rockcent.common.controller.BaseController;
import com.rockcent.common.domain.enumclass.Whether;
import com.rockcent.common.utils.BigDecimalUtils;
import com.rockcent.common.utils.RBeanUtils;
import com.rockcent.mall.lib.domain.*;
import com.rockcent.mall.lib.domain.enumclass.*;
import com.rockcent.mall.lib.dto.*;
import com.rockcent.mall.lib.helper.*;
import com.rockcent.mall.lib.repository.*;
import com.rockcent.service.FundService;
import com.rockcent.service.OrderService;
import com.rockcent.wechat.Routes;
import com.rockcent.wechat.helper.CustomerHelper;
import com.rockcent.wechat.service.OrderCommitService;
import org.apache.commons.lang3.EnumUtils;
import org.apache.commons.lang3.StringUtils;
import org.mockito.internal.matchers.CompareTo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * Created by HK on 16/10/8.
 *
 * 订单模块
 */
@RestController
@RequestMapping(value = Routes.API_PREFIX)
public class OrderController extends BaseController {

    private final Logger log = LoggerFactory.getLogger(OrderController.class);

    @Autowired
    private MerchantProductRepository merchantProductRepository;
    @Autowired
    private CustomerHelper customerHelper;
    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private QRCodeHelper qrCodeHelper;
    @Autowired
    private FundService fundService;
    @Autowired
    private VerificationHelper verificationHelper;
    @Autowired
    private MallOrderRepository mallOrderRepository;
    @Autowired
    private MerchantOrderRepository merchantOrderRepository;
    @Autowired
    private MerchantOrderItemRepository merchantOrderItemRepository;
    @Autowired
    private MerchantRepository merchantRepository;
    @Autowired
    private CustomerProductOrderRepository customerProductOrderRepository;
    @Autowired
    private MallRepository mallRepository;
    @Autowired
    private MerchantOrderVerificationRepository merchantOrderVerificationRepository;
    @Autowired
    private MerchantStoreCustomerRepository merchantStoreCustomerRepository;
    @Autowired
    private MerchantProductMerchantStoresRepository productMerchantStoresRepository;
    @Autowired
    private MerchantStoreRepository merchantStoreRepository;
    @Autowired
    private MerchantGiftPacketRepository merchantGiftPacketRepository;
    @Autowired
    private MerchantGiftPacketProductRepository merchantGiftPacketProductRepository;
    @Autowired
    private OrderCommitService orderCommitService;
    @Autowired
    private OrderEventHelper orderEventHelper;
    @Autowired
    private MerchantCouponRepository merchantCouponRepository;
    @Autowired
    private CustomerCouponWalletRepository customerCouponWalletRepository;
    @Autowired
    private MerchantCouponProductsRepository merchantCouponProductsRepository;
    @Autowired
    private ProductEventHelper productEventHelper;
    @Autowired
    private OrderService orderService;
    @Autowired
    private IntegrationCashCouponWalletRepository integrationCashCouponWalletRepository;
    @Autowired
    private MallFinancialSettingsRepository mallFinancialSettingsRepository;

//    x
//    @Transactional
//    @RequestMapping(value = "/test_service_settled", method = RequestMethod.GET)
//    public void testServiceSettled(String mallOrderNum, Long verifyNum) {
//
//        MallOrder mallOrder = mallOrderRepository.findByOrderNum(mallOrderNum);
//
//        List<MerchantOrder> merchantOrders = merchantOrderRepository.findByMallOrderNum(mallOrder.getOrderNum());
//        merchantOrders.forEach(merchantOrder -> {
//            fundService.serviceVerify(mallOrder, merchantOrder, verifyNum, false);
//        });
//    }


    /**
     * @api {post} /api/v2/order/commit 订单 产品提交订单
     * @apiGroup order
     * @apiVersion 1.0.0
     * @apiDescription 产品下单：当实付金额为 0 时，本订单只走钱包余额支付。
     * @apiParam {Long} buyProductListBuyId <code>必须参数</code>产品id
     * @apiParam {Long} buyProductListBuyCount <code>必须参数</code>产品购买数量数组
     * @apiParam {String} buyProductListBuyShoppingType <code>必须参数</code>产品购买物流类型数组 (枚举类型 : SHOP_PICKUP("到店自提"), SHIPPING("物流"), SHOP_PICKUP_AND_SHIPPING("物流及到店自取"))。当type=SHOP_PICKUP 时,storeId必须参数。 示例:[{"storeId":1,"type":"SHOP_PICKUP"},{"type":"SHIPPING"}]
     * @apiParam {String} buyProductListBuyCustomerShareCode 购买客户分享码
     * @apiParam {String} buyProductListBuyChannelSalesCode 购买渠道分销码
     * @apiParam {Long} buyCustomerShoppingAddressId <code>必须参数</code>收货地址id
     * @apiParam {Long} buyCouponWalletId 客户领取卡券id
     * @apiParam {Long} buyIntegrationCashCouponWalletId 客户领取积分现金卡券id
     * @apiParam {String} buyRemark 购买订单备注
     * @apiParam {Long} buyPromotionCodeId 推广码ID
     *
     * @apiSuccess {List} allowPaymentMethodList 允许使用的支付方式
     * @apiSuccess {BigDecimal} actualPrice 实付金额
     * @apiSuccess {orderNum} actualPrice 实付金额
     *
     * @apiParamExample {json} 服务下单:
     * {
     *     "buyProductList": [
     *         {
     *             "buyId":502,
     *             "buyCount":2
     *         },
     *         ...
     *     ],
     *     "buyCustomerShoppingId":1
     * }
     * @apiParamExample {json} 产品物流下单:
     * {
     *     "buyProductList": [
     *         {
     *             "buyId":789,
     *             "buyCount":13,
     *             "buyShippingType":"SHIPPING"
     *         },
     *         ...
     *     ],
     *     "buyCustomerShoppingId":1
     * }
     * @apiParamExample {json} 产品自提下单:
     * {
     *     "buyProductList": [
     *         {
     *             "buyId":791,
     *             "buyCount":3,
     *             "buyShippingType":"SHOP_PICKUP",
     *             "buyMerchantStoreId":23,
     *         },
     *         ...
     *     ],
     *     "buyCustomerShoppingId":1
     * }
     * @apiParamExample {json} 产品混合下单:
     * {
     *  "buyProductList": [
     *      {
     *          "buyId": 791,
     *          "buyCount": 21,
     *          "buyShippingType":"SHIPPING"
     *      },
     *      {
     *          "buyId":789,
     *          "buyCount":33,
     *          "buyShippingType":"SHIPPING"
     *      },
     *      {
     *          "buyId":502,
     *          "buyCount":2,
     *          "buyShippingType":"SHOP_PICKUP",
     *          "buyMerchantStoreId":20
     *      },
     *      {
     *          "buyId":610,
     *          "buyCount":2
     *      }
     *  ],
     *  "buyCustomerShoppingId":1
     * }
     * @apiParamExample {json} 产品下单-分享返利:
     * {
     *  "buyProductList": [
     *      {
     *          "buyId": 791,
     *          "buyCount": 21,
     *          "buyShippingType":"SHIPPING",
     *          "buyCustomerShareCode":"1237dsf79234fhier274924759244"
     *      },
     *  ]
     * }
     * @apiParamExample {json} 产品混合下单-全部字段:
     * {
     *  "buyProductList": [
     *      {
     *          "buyId": 791,
     *          "buyCount": 21,
     *          "buyShippingType":"SHIPPING"
     *      },
     *      {
     *          "buyId":789,
     *          "buyCount":33,
     *          "buyShippingType":"SHIPPING"
     *      },
     *      {
     *          "buyId":502,
     *          "buyCount":2,
     *          "buyShippingType":"SHOP_PICKUP",
     *          "buyMerchantStoreId":20,
     *          "buyChannelSalesCode":"7451a3120d917f7d3e5ddfcc5ecc0481"
     *      },
     *      {
     *          "buyId":610,
     *          "buyCount":2,
     *          "buyCustomerShareCode":"1237dsf79234fhier274924759244"
     *      }
     *  ],
     *  "buyCustomerShoppingId":1,
     *  "buyChannelSalesCode":"sdfur231r50224sfewafretulxtw"
     * }
     * @apiSuccessExample {json} Success-Response:
     * {
     *  "code": "1",
     *  "desc": "成功",
     *  "data":{
     *      "orderNum":"20161212032323234876897",
     *      "actualPrice": 374.2,
     *      "allowPaymentMethodList": [
     *          "BALANCE",
     *          "WECHAT"
     *      ]
     *  }
     * }
     */
    @Transactional
    @RequestMapping(value = Routes.ORDER_COMMIT, method = RequestMethod.POST)
    public JsonResult commit(@RequestBody BuyOrderDto dto, HttpServletRequest request) {
        log.info("============================>dto:{}", dto);
        CustomerDto customerDto = customerHelper.getSession(request);
        RestDoing doing = jsonResult -> {
            dto.setBuyCommitType(OrderCommitType.COMMON);
            orderCommitService.commit(dto, customerDto, jsonResult);
        };
        return doing.go(dto, customerDto, request, objectMapper, log);
    }


    /**
     * @api {post} /api/v2/order/gift_packet_commit 订单 礼包提交订单
     * @apiGroup order
     * @apiVersion 1.0.0
     * @apiParam {Long} buyGiftPacketId 购买礼包id
     * @apiParam {Long} buyCount 购买礼包数量
     * @apiParam {Long} buyCustomerShoppingId 购买人收货地址 id
     * @apiParam {String} buyCustomerShareCode 购买人分享码
     * @apiParam {Long} buyIntegrationCashCouponWalletId 客户领取现金券id
     *
     * @apiParamExample {json} 礼包下单:
     * {
     *  "buyGiftPacketId":197,
     *  "buyCount":1,
     *  "buyCustomerShoppingId":1,
     *  "buyCustomerShareCode":"1237dsf79234fhier274924759244",
     *  "buyCouponWalletId":123
     * }
     * @apiSuccessExample {json} Success-Response:
     * {
     *  "code": "1",
     *  "desc": "成功",
     *  "data":{
     *      orderNum:"20161212032323234876897"
     *  }
     * }
     */
    @Transactional
    @RequestMapping(value = Routes.ORDER_GIFT_PACKET_COMMIT, method = RequestMethod.POST)
    public JsonResult giftPackageCommit(@RequestBody BuyGiftPacketDto dto, HttpServletRequest request) {
        CustomerDto customerDto = customerHelper.getSession(request);
        RestDoing doing = jsonResult -> {
            if (dto.getBuyGiftPacketId() == null) {
                jsonResult.errorParam("下单礼包id不能为空",log);
                return;
            }
            MerchantGiftPacket merchantGiftPacket = merchantGiftPacketRepository.findOne(dto.getBuyGiftPacketId());
            if (merchantGiftPacket == null) {
                jsonResult.remind(MerchantGiftPacket.REMIND_RECORD_IS_NOT_EXIST,log);
                return;
            }
            if (merchantGiftPacket.getStatus() != GiftPacketStatus.S2_SELLING) {
                jsonResult.remind("下单礼包状态异常",log);
                return;
            }

            Mall mall = mallRepository.getOne(customerDto.getMallId());
            MallFinancialSettings mallFinancialSettings = mallFinancialSettingsRepository.findTop1ByMallIdAndIsDeleteOrderByLastUpdatedDesc(mall.getId(), Whether.NO);

            BigDecimal shareFee = merchantGiftPacket.getShareFee().multiply(new BigDecimal(dto.getBuyCount())).setScale(3, BigDecimal.ROUND_HALF_UP);


            log.info("============================>shareFee:{}",shareFee);
            BuyOrderDto buyOrderDto = new BuyOrderDto();
            buyOrderDto.setShareFee(shareFee);
            buyOrderDto.setShareRate(mallFinancialSettings.getShareFeeRate());
            List<BuyProductDto> buyProductDtoList = new ArrayList<>();
            List<MerchantGiftPacketProduct> merchantGiftPacketProductList = merchantGiftPacketProductRepository.findByPacketIdAndIsDelete(merchantGiftPacket.getId(), Whether.NO);
            List<MerchantGiftPacketProduct> merchantGiftPacketProductListSort = new ArrayList<>();// 产品排序,把分销产品排在最前面
            merchantGiftPacketProductListSort.addAll(merchantGiftPacketProductList.stream().filter(merchantGiftPacketProduct -> !Objects.equals(merchantGiftPacketProduct.getProductId(), merchantGiftPacketProduct.getMarketId())).collect(Collectors.toList())); // 分销产品
            merchantGiftPacketProductListSort.addAll(merchantGiftPacketProductList.stream().filter(merchantGiftPacketProduct -> Objects.equals(merchantGiftPacketProduct.getProductId(), merchantGiftPacketProduct.getMarketId())).collect(Collectors.toList())); // 自营产品


            for (MerchantGiftPacketProduct merchantGiftPacketProduct : merchantGiftPacketProductListSort) {
                BuyProductDto buyProductDto = new BuyProductDto();
                buyProductDto.setBuyId(merchantGiftPacketProduct.getProductId());
                buyProductDto.setBuyCount(merchantGiftPacketProduct.getUseNumber() * dto.getBuyCount());
                buyProductDto.setBuyCustomerShareCode(dto.getBuyCustomerShareCode());
                buyProductDto.setBuyShippingType(ProductShippingType.SHIPPING);

                Product product = merchantProductRepository.findByIdAndIsDelete(merchantGiftPacketProduct.getProductId(), Whether.NO);
                if (product == null) {
                    jsonResult.remind(String.format("产品 id : %d,记录不存在,请检查礼包数据正确性", merchantGiftPacketProduct.getProductId()),log);
                    return;
                }
                if (shareFee.compareTo(BigDecimal.ZERO) > -1 && !Objects.equals(merchantGiftPacketProduct.getMarketId(), merchantGiftPacketProduct.getProductId())) { // 分销产品 先用佣金抵消返利
                    Product supplierProduct = merchantProductRepository.findByIdAndIsDelete(product.getMarketId(), Whether.NO);

                    BigDecimal supplierResellFee = supplierProduct.getResellFee().multiply(new BigDecimal(buyProductDto.getBuyCount()));
                    if (supplierProduct.getSellPrice().compareTo(merchantGiftPacketProduct.getPacketPrice()) == 1) {
                        BigDecimal packetResellFee = supplierProduct.getSellPrice().subtract(merchantGiftPacketProduct.getPacketPrice());
                        supplierResellFee = supplierProduct.getResellFee().subtract(packetResellFee).multiply(new BigDecimal(buyProductDto.getBuyCount()));
                    }

                    if (shareFee.compareTo(supplierResellFee) >= 0) { // 返利大于佣金 || 返利等于佣金
                        buyProductDto.setShareFee(supplierResellFee);
                        shareFee = shareFee.subtract(supplierResellFee);
                    } else if (shareFee.compareTo(supplierResellFee) == -1) { // 返利小于佣金
                        buyProductDto.setShareFee(shareFee);
                        shareFee = shareFee.subtract(shareFee);
                    }

                    buyProductDto.setPacketResellFee(supplierResellFee);
                }

                if (shareFee.compareTo(BigDecimal.ZERO) > -1 && Objects.equals(merchantGiftPacketProduct.getMarketId(), merchantGiftPacketProduct.getProductId())) { // 自营产品

                    // 扣除平台服务费可分配返利值
                    BigDecimal newShareFee = merchantGiftPacketProduct.getPacketPrice().subtract(merchantGiftPacketProduct.getPacketPrice().multiply(BigDecimalUtils.divide(mallFinancialSettings.getBusinessServiceFeeRate(), "100"))).multiply(new BigDecimal(buyProductDto.getBuyCount()));

                    if (shareFee.compareTo(newShareFee) >= 0) { // 返利大于售价 || // 返利等于售价
                        buyProductDto.setShareFee(newShareFee);
                        shareFee = shareFee.subtract(newShareFee);
                    } else {
                        buyProductDto.setShareFee(shareFee);
                        shareFee = shareFee.subtract(shareFee);
                    }
                }

                buyProductDto.setSellPrice(merchantGiftPacketProduct.getPacketPrice());
                buyProductDtoList.add(buyProductDto);
            }

            buyOrderDto.setBuyGiftPacketSellPrice(merchantGiftPacket.getSellPrice());
            buyOrderDto.setBuyGiftPacketId(dto.getBuyGiftPacketId());
            buyOrderDto.setBuyCommitType(OrderCommitType.GIFT_PACKET);
            buyOrderDto.setBuyCustomerShoppingId(dto.getBuyCustomerShoppingId());
            buyOrderDto.setBuyProductList(buyProductDtoList);
            buyOrderDto.setBuyGiftPacketCount(dto.getBuyCount());
//            buyOrderDto.setBuyIntegrationCashCouponWalletId(dto.getBuyIntegrationCashCouponWalletId());// 使用现金券
            buyOrderDto.setBuyGiftPacketName(merchantGiftPacket.getName());
            log.info("============================>shareFee:{}",shareFee);
            orderCommitService.commit(buyOrderDto, customerDto, jsonResult);

        };
        return doing.go(dto, customerDto, request, objectMapper, log);
    }

    /**
     * @api {post} /api/v2/order/calculated_price 订单 订单计费
     * @apiGroup order
     * @apiVersion 1.0.0
     * @apiParam {Long} buyProductListBuyId <code>必须参数</code>产品id
     * @apiParam {Long} buyProductListBuyCount <code>必须参数</code>产品购买数量数组
     * @apiParam {Long} buyCouponWalletId 客户卡券id
     * @apiParam {Long} buyCashId 现金卷id
     * @apiParam {Long} buyIntegrationCashCouponId 客户现金卷id
     *
     * @apiSuccessExample {json} Success-Response:
     * {
     *  "code": "1",
     *  "desc": "成功",
     *  "data": {
     *      "couponDiscountPrice": 10,
     *      "discountPrice": 90.72,
     *      "cashPrice": 10,
     *      "totalPrice": 100.72
     *  }
     * }
     **/
    @RequestMapping(value = Routes.ORDER_CALCULATED_PRICE, method = RequestMethod.POST)
    public JsonResult calculatedPrice(@RequestBody BuyOrderDto dto, HttpServletRequest request) {
        CustomerDto customerDto = customerHelper.getSession(request);
        RestDoing doing = jsonResult -> {
            dto.setBuyCustomerId(customerDto.getId());

            // 检查购买产品字段
            for (int i = 0; i < dto.getBuyProductList().size(); i++) {
                BuyProductDto buyProduct = dto.getBuyProductList().get(i);
                Product product = merchantProductRepository.findOne(buyProduct.getBuyId());
                List<String> ignoreFieldList = new ArrayList<>();
                if (dto.getBuyCommitType() == OrderCommitType.GIFT_PACKET) {
                    ignoreFieldList.add("resellFee");
                    ignoreFieldList.add("shareFee");
                }
                // 以上检验通过,把所有关于产品的属性copy一次
                RBeanUtils.copyProperties(product, buyProduct, ignoreFieldList, false);
            }
            // 购买产品 List 数据整合, 自营产品marketId 为空,设置为零
            List<BuyProductDto> buyProductDtoList = dto.getBuyProductList().stream().map(buyProductDto -> {
                if (buyProductDto.getMarketId() == null) {
                    buyProductDto.setMarketId(0L);
                }
                return buyProductDto;
            }).collect(Collectors.toList());

            List<MerchantCouponProducts> merchantCouponProductsList = null;
            MerchantCoupon merchantCoupon = null;
            if (dto.getBuyCouponWalletId() != null) {
                CustomerCouponWallet customerCouponWallet = customerCouponWalletRepository.findByIdAndCustomerIdAndStatus(dto.getBuyCouponWalletId(), customerDto.getId(), CustomerCouponWalletStatus.TO_USE);
                merchantCoupon = merchantCouponRepository.findByIdAndMerchantId(customerCouponWallet.getCouponId(), customerCouponWallet.getMerchantId());
                merchantCouponProductsList = merchantCouponProductsRepository.findByCouponId(merchantCoupon.getId());
            }

            BuyOrderDto buyOrderDto = new BuyOrderDto();
            if (dto.getBuyIntegrationCashCouponWalletId() != null && dto.getBuyCashId() != null) {
                IntegrationCashCouponWallet integrationCashWallet = integrationCashCouponWalletRepository.findByIdAndCashCouponId(dto.getBuyIntegrationCashCouponWalletId(), dto.getBuyCashId());
                if (integrationCashWallet != null) {
                    buyOrderDto.setCashPrice(integrationCashWallet.getFaceValue());
                }
            }
            buyOrderDto.setTotalPrice(OrderHelper.SINGLEONE.calculatedMallOrderSellTotalAmount(buyProductDtoList));
            buyOrderDto.setDiscountPrice(OrderHelper.SINGLEONE.calculatedMallOrderDiscountTotalAmount(buyProductDtoList, merchantCouponProductsList, merchantCoupon).subtract(buyOrderDto.getCashPrice()));
            buyOrderDto.setCouponDiscountPrice(OrderHelper.SINGLEONE.calculatedMallOrderCouponDiscountAmount(buyProductDtoList, merchantCouponProductsList, merchantCoupon));
            jsonResult.data = buyOrderDto;
        };
        return doing.go(dto, request, objectMapper, log);
    }


    /**
     * @api {post} /api/v2/order/cancel 取消订单
     * @apiGroup order
     * @apiVersion 1.0.0
     *
     * @apiHeader {String} userToken 用户Token
     * @apiHeader {String} domain 平台域名
     *
     * @apiParam {String} orderNum 平台订单号
     *
     * @apiSuccess {Long} data 平台订单号
     *
     * @apiSuccessExample {json} Success-Response:
     * {
     *  "code": "1",
     *  "desc": "成功",
     *  "data": "1608030122342"
     * }
     */
    @Transactional
    @RequestMapping(value = Routes.ORDER_CANCEL, method = RequestMethod.POST)
    public JsonResult cancel(String orderNum, HttpServletRequest request) {
        CustomerDto customerDto = customerHelper.getSession(request);
        RestDoing doing = jsonResult -> {
            if (orderNum == null) {
                jsonResult.remind("平台订单号不能为空",log);
                return;
            }
            orderService.cancel(customerDto, orderNum);
        };
        return doing.go(request, log);
    }

    /**
     * @api {put} /api/v2/order/create/verify/code 创建核销码
     * @apiGroup order
     *
     * @apiHeader {String} domain <code>必须参数</code>对应平台C端域名
     * @apiHeader {String} userToken <code>必须参数</code>用户Token
     *
     * @apiParam {String} merchantOrderNum 订单号
     * @apiParam {Long} useNum 使用数量 产品为商品到店自提时,为产品购买数量
     *
     * @apiSuccess {String} verifyCode 核销码
     * @apiSuccess {String} qrCodeUrl 二维码图片 页面显示格式为:
     *
     * @apiSuccessExample {json} Success-Response:
     *  {
     *       "code": 1,
     *       "desc": "成功"
     *       "data": {
     *          "verifyCode": "784317",
     *          "qrcCodeUrl": "dsfgjkopjgrjnerngoogq45wjth[nniwjbbjpwjpobsldnfbsnbonrostbnsnbnsbnoisnbo"
     *       }
     *   }
     **/
    @Transactional
    @RequestMapping(value = Routes.ORDER_CREATE_VERIFY_CODE, method = RequestMethod.PUT)
    public JsonResult orderCreateVerifyCode(HttpServletRequest request, @RequestBody QrCodeDto dto) {
        CustomerDto customerDto = customerHelper.getSession(request);
        RestDoing doing = jsonResult -> {
            if (StringUtils.isBlank(dto.getMerchantOrderNum())) {
                jsonResult.remind("订单号不能为空",log);
                return;
            }
            if (dto.getUseNum() == null) {
                jsonResult.remind("使用数量不能为空",log);
                return;
            }
            MerchantOrder merchantOrder = merchantOrderRepository.findByOrderNumAndMallId(dto.getMerchantOrderNum(), customerDto.getMallId());
            if (merchantOrder == null) {
                jsonResult.remind(MerchantOrder.REMIND_RECORD_IS_NOT_EXIST,log);
                return;
            }
            if (MerchantOrderMerchantRole.DISTRIBUTOR == merchantOrder.getMerchantRole()) {
                merchantOrder = merchantOrderRepository.findByMarketOrderNumAndMerchantRoleAndSourceType(merchantOrder.getMarketOrderNum(), MerchantOrderMerchantRole.SUPPLIER, MerchantOrderSourceType.MARKET);
            }
            CustomerProductOrder customerProductOrder = customerProductOrderRepository.findByMerchantOrderNumAndCustomerId(merchantOrder.getOrderNum(), customerDto.getId());
            if (OrderType.GOODS == merchantOrder.getOrderType()) {
                if (OrderStatus.WAIT_SHOP_PICKUP != merchantOrder.getStatus()) {
                    jsonResult.remind("订单还没完成支付",log);
                    return;
                }
                if (customerProductOrder != null && CustomerProductOrderStatus.USED == customerProductOrder.getStatus()) {
                    jsonResult.remind("此订单已经使用",log);
                    return;
                }
            }

            if (ProductShippingType.SHIPPING == merchantOrder.getProductShoppingType()) {
                jsonResult.remind("此订单属于物流快递 不能生成二维码",log);
                return;
            }

            if (OrderType.SERVICE == merchantOrder.getOrderType()) {
                if (SettlementStatus.SETTLED != merchantOrder.getSettleStatus()) {
                    if (OrderStatus.WAIT_USE == merchantOrder.getStatus() || OrderStatus.PART_USE == merchantOrder.getStatus()) {
                        List<MerchantOrderItem> merchantOrderItemList = merchantOrderItemRepository.findByMerchantOrderIdAndMerchantId(merchantOrder.getId(), merchantOrder.getMerchantId());
                        if (merchantOrderItemList.size() == 0) {
                            jsonResult.remind("订单有误",log);
                            return;
                        }
                        MerchantOrderItem merchantOrderItem = merchantOrderItemList.get(0);
                        Long surplusCount = merchantOrderItem.getBuyCount() - merchantOrderItem.getVerifyCount();
                        if (surplusCount < dto.getUseNum()) {
                            jsonResult.remind("数量不够",log);
                            return;
                        }
                    }
                }
            }

            if (customerProductOrder == null) {
                customerProductOrder = new CustomerProductOrder();
            }

            Mall mall = mallRepository.findOne(customerDto.getMallId());
            String host = mall.getCustomerClientDomain();
            if (StringUtils.isBlank(host)) {
                host = mall.getMobileHostName();
            }
            Integer verifyCode = customerHelper.verifyCode(VerifyType.ORDER);
            String verifyKey = customerHelper.customerCouponCodeMd5(merchantOrder.getMerchantId(), customerDto.getId(), merchantOrder.getId(), verifyCode);
            StringBuilder url = new StringBuilder();
            url.append("http://").append(host).append("/").append("?useNum=").append(dto.getUseNum()).append("&verifyKey=").append(verifyKey).append("&merchantId=").append(merchantOrder.getMerchantId());
            String qrcCodeUrl = qrCodeHelper.createBase64QRCode(url.toString());
            customerProductOrder.setQrcCodeUrl(qrcCodeUrl);
            customerProductOrder.setVerifyCode(String.valueOf(verifyCode));
            customerProductOrder.setVerifyKey(verifyKey);
            customerProductOrder.setUseNum(dto.getUseNum());
            customerProductOrder.setStatus(CustomerProductOrderStatus.TO_USE);
            customerProductOrder.setMerchantOrderNum(merchantOrder.getOrderNum());
            customerProductOrder.setMerchantId(merchantOrder.getMerchantId());
            customerProductOrder.setMallId(merchantOrder.getMallId());
            customerProductOrder.setCustomerId(customerDto.getId());
            customerProductOrder = customerProductOrderRepository.save(customerProductOrder);

            //订单事件记录

            jsonResult.data = customerProductOrder;

        };
        return doing.go(request, log);
    }

    /**
     * @api {put} /api/v2/order/scan/verify 扫码核销
     * @apiGroup order
     *
     * @apiHeader {String} domain <code>必须参数</code>对应平台C端域名
     * @apiHeader {String} userToken <code>必须参数</code>用户Token
     *
     * @apiParam {String} verifyKey <code>必传参数</code> 核销兑换码
     * @apiParam {Long} useNum <code>必传参数</code> 使用数量  订单为商品到店自提,默认传1
     * @apiParam {Long} verifierId <code>必传参数</code> 核销员ID
     * @apiParam {Long} merchantId <code>必传参数</code> 商家ID
     *
     * @apiSuccess {String} code 1:代表成功, 3:代表温馨提示, 5:代表核销员工不存在
     *
     * @apiSuccessExample {json} Success-Response:
     *      {
     *      "code": 1,
     *      "desc" : "成功",
     *      "data" : {
     *          23534264564356
     *      }
     *      }
     */
    @Transactional
    @RequestMapping(value = Routes.ORDER_SCAN_VERIFY, method = RequestMethod.PUT)
    public JsonResult orderScanVerify(HttpServletRequest request, @RequestBody QrCodeDto dto) {
        CustomerDto customerDto = customerHelper.getSession(request);
        RestDoing doing = jsonResult -> {
            String dtoVerifyKey = dto.getVerifyKey();
            if (StringUtils.isBlank(dtoVerifyKey)) {
                jsonResult.remind("核销兑换码 不能为空",log);
                return;
            }
            Long verifierId = dto.getVerifierId();
            if (verifierId == null) {
                jsonResult.remind("核销员工ID 不能为空",log);
                return;
            }
            Long dtoUseNum = dto.getUseNum();
            if (dtoUseNum == null) {
                jsonResult.remind("使用数量 不能为空",log);
                return;
            }
            Long dtoMerchantId = dto.getMerchantId();
            if (dtoMerchantId == null) {
                jsonResult.remind("商家ID 不能为空",log);
                return;
            }
            MerchantStoreCustomer merchantStoreCustomer = merchantStoreCustomerRepository.findByVerifyPersonIdAndMerchantIdAndIsDelete(verifierId, dtoMerchantId, Whether.NO);
            if (merchantStoreCustomer == null) {
                jsonResult.custom("5", "核销员工不存在", log);
                return;
            }

            CustomerProductOrder customerProductOrder = customerProductOrderRepository.findByVerifyKeyAndStatusAndIsDelete(dtoVerifyKey, CustomerProductOrderStatus.TO_USE, Whether.NO);
            if (customerProductOrder == null) {
                jsonResult.remind("此二维码无效",log);
                return;
            }
            String customerProductOrderMerchantOrderNum = customerProductOrder.getMerchantOrderNum();
            MerchantOrder merchantOrder = merchantOrderRepository.findByOrderNumAndMallId(customerProductOrderMerchantOrderNum, customerProductOrder.getMallId());
            if (merchantOrder == null) {
                jsonResult.remind("此二维码订单不存在",log);
                return;
            }

            if (ProductShippingType.SHIPPING == merchantOrder.getProductShoppingType()) {
                jsonResult.remind("此订单属于物流快递 二维码无效",log);
                return;
            }

            Long merchantStoreCustomerStoreId = merchantStoreCustomer.getStoreId();
            Long merchantOrderMerchantId = merchantOrder.getMerchantId();
            Long merchantOrderMallId = merchantOrder.getMallId();
            MerchantStore merchantStore = merchantStoreRepository.findByIdAndMerchantIdAndMallIdAndIsDelete(merchantStoreCustomerStoreId, merchantOrderMerchantId, merchantOrderMallId, Whether.NO);
            if (merchantStore == null) {
                jsonResult.remind("商家不存在此间门店",log);
                return;
            }

            Long customerDtoMallId = customerDto.getMallId();
            String merchantOrderMallOrderNum = merchantOrder.getMallOrderNum();

            List<MerchantOrderItem> merchantOrderItemList = merchantOrderItemRepository.findByMerchantOrderIdAndMerchantId(merchantOrder.getId(), merchantOrderMerchantId);
            OrderStatus merchantOrderStatus = merchantOrder.getStatus();
            String marketOrderNum = merchantOrder.getMarketOrderNum();
            String customerProductOrderVerifyCode = customerProductOrder.getVerifyCode();
            Long customerProductOrderCustomerId = customerProductOrder.getCustomerId();
            String merchantStoreName = merchantStore.getName();

            MallOrder mallOrder = mallOrderRepository.findByOrderNumAndMallId(merchantOrderMallOrderNum, customerDtoMallId);

            if (OrderType.SERVICE == merchantOrder.getOrderType()) {
                MerchantOrderItem merchantOrderItem = merchantOrderItemList.get(0);
                if (OrderStatus.WAIT_USE == merchantOrderStatus || OrderStatus.PART_USE == merchantOrderStatus) {

                    if (merchantOrderItemList.size() == 0) {
                        jsonResult.remind("此订单有误,请联系客户人员",log);
                        return;
                    }

                    if (OrderStatus.WAIT_USE != merchantOrderStatus && OrderStatus.PART_USE != merchantOrderStatus) {
                        jsonResult.remind("订单还没完成支付",log);
                        return;
                    }
                    Long merchantOrderItemVerifyCount = merchantOrderItem.getVerifyCount();
                    Long merchantOrderItemBuyCount = merchantOrderItem.getBuyCount();
                    if (Objects.equals(merchantOrderItemBuyCount, merchantOrderItemVerifyCount)) {
                        jsonResult.remind("二维码有误,请重新生成!",log);
                        return;
                    }
                    Product product = merchantProductRepository.findOne(merchantOrderItem.getProductId());
                    if (ProductMerchantStoreType.PART == product.getProductMerchantStoreType()) {
                        List<ProductMerchantStores> merchantStoresList = productMerchantStoresRepository.findByProductIdAndMerchantId(product.getId(), merchantOrderMerchantId);
                        List<Long> storeIds = merchantStoresList.stream().map(ProductMerchantStores::getMerchantStoreId).collect(Collectors.toList());
                        if (!storeIds.contains(merchantStoreCustomerStoreId)) {
                            jsonResult.remind("此核销员不是本店核销员工",log);
                            return;
                        }
                    }

                    if (mallOrder.getGiftId() != null) {
                        fundService.giftPacketVerify(mallOrder, merchantOrder, dtoUseNum);
                    } else {
                        fundService.serviceVerify(mallOrder, merchantOrder, dtoUseNum, false);
                    }
                }
                //记录核销记录
                MerchantOrderVerification orderVerification = verificationHelper.merchantOrderVerificationSave(merchantOrder, merchantOrderItem, dtoUseNum, customerProductOrderVerifyCode, customerDto.getId(), merchantOrderItem.getLogoUrl(), merchantStoreName, OrderVerificationWay.SCAN, merchantOrder.getMerchantRole());
                merchantOrderVerificationRepository.save(orderVerification);
                //记录分销商核销记录
                MerchantOrderMerchantRole merchantOrderItemMerchantRole = merchantOrderItem.getMerchantRole();
                if (merchantOrderItemMerchantRole == MerchantOrderMerchantRole.SUPPLIER) {
                    MerchantOrder marketOrder = merchantOrderRepository.findByMarketOrderNumAndMerchantRole(marketOrderNum, MerchantOrderMerchantRole.DISTRIBUTOR);
                    List<MerchantOrderItem> orderItemList = merchantOrderItemRepository.findByMerchantOrderIdAndMerchantId(marketOrder.getId(), marketOrder.getMerchantId());
                    MerchantOrderVerification verification = verificationHelper.merchantOrderVerificationSave(marketOrder, orderItemList.get(0), customerProductOrder.getUseNum(), customerProductOrderVerifyCode, customerProductOrderCustomerId, merchantOrderItem.getLogoUrl(), merchantStoreName, OrderVerificationWay.SCAN, marketOrder.getMerchantRole());
                    merchantOrderVerificationRepository.save(verification);
                }
                //产品事件记录
                productEventHelper.productEventSave(merchantOrder, merchantOrderItem, customerProductOrder.getUseNum(), ProductEventType.VERIFIED);
            }
            if (OrderType.GOODS == merchantOrder.getOrderType()) {
                if (OrderStatus.WAIT_SHOP_PICKUP != merchantOrderStatus) {
                    jsonResult.remind("订单还没完成支付",log);
                    return;
                }
                if (merchantStoreCustomerStoreId != merchantOrder.getMerchantStoreId()) {
                    jsonResult.remind("此核销员不是本店核销员工",log);
                    return;
                }

                for (MerchantOrderItem orderItem : merchantOrderItemList) {
                    Product product = merchantProductRepository.findOne(orderItem.getProductId());
                    //记录核销记录
                    MerchantOrderVerification orderVerification = verificationHelper.merchantOrderVerificationSave(merchantOrder, orderItem, orderItem.getBuyCount(), customerProductOrderVerifyCode, customerDto.getId(), product.getLogoUrl(), merchantStoreName, OrderVerificationWay.SCAN, merchantOrder.getMerchantRole());
                    orderVerification = merchantOrderVerificationRepository.save(orderVerification);
                    //记录分销商核销记录
                    MerchantOrderMerchantRole orderItemMerchantRole = orderItem.getMerchantRole();
                    if (orderItemMerchantRole == MerchantOrderMerchantRole.SUPPLIER) {
                        MerchantOrder marketOrder = merchantOrderRepository.findByMarketOrderNumAndMerchantRole(marketOrderNum, MerchantOrderMerchantRole.DISTRIBUTOR);

                        Long productId = orderItem.getProductId();
                        Product productDistribute = merchantProductRepository.findByMarketIdAndMerchantId(productId, marketOrder.getMerchantId());
                        String orderItemMarketOrderNum = orderItem.getMarketOrderNum();
                        MerchantOrderItem distributorMerchantOrderItem = merchantOrderItemRepository.findByMarketOrderNumAndMerchantRoleAndProductId(orderItemMarketOrderNum, MerchantOrderMerchantRole.DISTRIBUTOR, productDistribute.getId());
                        MerchantOrderMerchantRole marketOrderMerchantRole = marketOrder.getMerchantRole();
                        String orderItemLogoUrl = orderItem.getLogoUrl();
                        Long distributorMerchantOrderItemBuyCount = distributorMerchantOrderItem.getBuyCount();
                        MerchantOrderVerification verification = verificationHelper.merchantOrderVerificationSave(marketOrder, distributorMerchantOrderItem, distributorMerchantOrderItemBuyCount, customerProductOrderVerifyCode, customerProductOrderCustomerId, orderItemLogoUrl, merchantStoreName, OrderVerificationWay.SCAN, marketOrderMerchantRole);
                        verification = merchantOrderVerificationRepository.save(verification);


                    }
                    //产品事件记录
                    productEventHelper.productEventSave(merchantOrder, orderItem, orderItem.getBuyCount(), ProductEventType.VERIFIED);
                }
                //商品订单到店自提核销结算
                if (mallOrder.getGiftId() != null) {
                    fundService.giftPacketVerify(mallOrder, merchantOrder, null);
                } else {
                    fundService.productVerify(mallOrder, merchantOrder);
                }
            }

            customerProductOrder.setStatus(CustomerProductOrderStatus.USED);
            customerProductOrderRepository.save(customerProductOrder);

            // 订单事件记录
            orderEventHelper.saveOrderEvent(merchantOrder, OrderEventType.VERIFY_SCAN, merchantStoreCustomer.getNickName(), merchantStoreCustomer.getId());
            jsonResult.data = customerProductOrderMerchantOrderNum;
        };
        return doing.go(request, log);
    }

    /**
     * @api {get} /api/v2/order/scan/roll 订单扫码核销轮询
     * @apiGroup order
     *
     * @apiHeader {String} domain <code>必须参数</code>对应平台C端域名
     * @apiHeader {String} userToken <code>必须参数</code>用户Token
     *
     * @apiParam {String} verifyCode <code>必传参数</code> 兑换码
     * @apiParam {Long} merchantOrderNum <code>必传参数</code> 订单号
     *
     * @apiSuccessExample {json} Success-Response:
     *  {
     *      "code": "1",
     *      "desc": "成功",
     *      "data": true
     *  }
     */
    @RequestMapping(value = Routes.ORDER_SCAN_ROlL, method = RequestMethod.GET)
    public JsonResult orderScanRoll(HttpServletRequest request, QrCodeDto dto) {
        CustomerDto customerDto = customerHelper.getSession(request);

        RestDoing doing = jsonResult -> {
            if (StringUtils.isBlank(dto.getMerchantOrderNum())) {
                jsonResult.remind("订单号不能为空！",log);
                return;
            }
            if (StringUtils.isBlank(dto.getVerifyCode())) {
                jsonResult.remind("核销码不能为空！",log);
                return;
            }
//            log.info("======================>customerDto:{}",customerDto);
//            log.info("======================>QrCodeDto:{}",dto);

            CustomerProductOrder customerProductOrder = customerProductOrderRepository.findByCustomerIdAndVerifyCodeAndStatusAndIsDelete(customerDto.getId(), dto.getVerifyCode(), CustomerProductOrderStatus.USED, Whether.NO);
            if (customerProductOrder == null) {
                jsonResult.errorParam(CustomerProductOrder.REMIND_RECORD_IS_NOT_EXIST,log);
                return;
            }
            jsonResult.setData(true);
        };
        return doing.go(request, log);
    }

    /**
     * @api {get} /api/v2/order/list 订单列表
     * @apiGroup order
     * @apiVersion 1.0.0
     *
     * @apiHeader {String} userToken 用户Token
     * @apiHeader {String} domain 平台域名
     * @apiParam {Integer} pageNo 页码
     * @apiParam {Integer} pageSize 每页记录数
     * @apiParam {String} status 订单状态，ALL(全部，查待评价时用),WAIT_PAYING("待支付"), CANCEL("取消"), WAIT_SHIPPED("等待发货"), SHIPPED("已发货 = 待收货"), WAIT_SHOP_PICKUP("到店自提"="待自提"),WAIT_USE("待使用"), FINISHED("已完成"),OVERDUE("已过期")
     * @apiParam {String} evaluateStatus 评价状态：DEFAULT("默认"),WAIT_EVALUATE("待评价"),HAD_EVALUATE("已评价");
     *
     * @apiSuccess {Long} id 订单ID
     * @apiSuccess {Long} version 版本
     * @apiSuccess {Date} dateCreated 创建时间
     * @apiSuccess {Date} laseUpdated 更新时间
     * @apiSuccess {Long} mall 平台id
     * @apiSuccess {BigDecimal} totalAmount 总金额
     * @apiSuccess {BigDecimal} discountTotalAmount 折扣金额
     * @apiSuccess {BigDecimal} oriTotalAmount 源总金额
     * @apiSuccess {String} orderNum 平台订单号
     * @apiSuccess {String} shoppingAddress 收货地址
     * @apiSuccess {String} shoppingMan 收货人
     * @apiSuccess {String} shoppingManPhone 收货人电话号码
     * @apiSuccess {String} status 订单状态 WAIT_PAYING(\"待支付\"), CANCEL(\"取消\"), PAYED(\"已支付\"), WAIT_SHIPPED(\"等待发货\"), SHIPPED(\"已发货\"), SHOP_PICKUP(\"到店自提\"), PART_SHOP_PICKUP(\"部分到店自提\"), CONFIRM_PICKUP(\"确认自提\"), CONFIRM(\"已确认\"), WAIT_USE(\"待使用\"), PART_USE(\"部分使用\"), USED(\"已使用\"), FINISHED(\"已完成\"), APPLY_REJECT(\"申请退货\"), FINISHED_REJECT(\"已完成退货\"), APPLY_REFUND(\"申请退款\"), FINISHED_REFUND(\"已完成退款\"),WAIT_STOCK待备货
     * @apiSuccess {String} orderType 订单类型 GOODS(\"实物商品\"), SERVICE(\"到店服务\")
     * @apiSuccess {String} remark 备注
     * @apiSuccess {Long} customerId 客户id
     * @apiSuccess {String} mallSourceType 应用类型：平台或商家
     * @apiSuccess {BigDecimal} marketServiceRate 分销市场服务费
     * @apiSuccess {BigDecimal} actualPrice 跨站实收金额
     * @apiSuccess {String} platformServiceFeeRates 跨站服务费
     * @apiSuccess {String} paymentTransaction 支付流水号
     * @apiSuccess {String} giftName 礼包名称
     * @apiSuccess {Long} giftId 礼包id
     * @apiSuccess {Long} giftNum 礼包数量
     * @apiSuccess {Long} payUrl 支付URL
     * @apiSuccess {Long} salesCode 分销码
     * @apiSuccess {List} productList 商品列表 礼包 或 产品
     *
     * @apiSuccess {Long} merchantOrderId 订单产品：商家订单 id
     * @apiSuccess {Long} merchantId 订单产品：商家 id
     * @apiSuccess {Long} productId 订单产品：产品 id
     * @apiSuccess {String} productName 订单产品：产品名称
     * @apiSuccess {String} logoUrl 订单产品：产品图片
     * @apiSuccess {Date} productDateDisabled 订单产品：产品过期退时间
     * @apiSuccess {String} productRefundable 订单产品：是否支持过期退 YES("是"), NO("否")
     * @apiSuccess {Boolean} productRefundableIsRun 订单产品：是否已执行自动退款
     * @apiSuccess {BigDecimal} resellFee 订单产品：产品分销佣金
     * @apiSuccess {BigDecimal} shareFee 订单产品：产品分享返利
     * @apiSuccess {String} serveRate 订单产品：服务费比率
     * @apiSuccess {String} shareRate 订单产品：M/D分享比率
     * @apiSuccess {BigDecimal} singleAmount 订单产品：产品单价
     * @apiSuccess {Long} buyCount 订单产品：购买数量
     * @apiSuccess {BigDecimal} totalAmount 订单产品：合计金额
     * @apiSuccess {Long} mallId 订单产品：平台id
     * @apiSuccess {String} mallOrderNum 订单产品：平台订单号
     * @apiSuccess {Long} merchantStoreId 订单产品：关联门店id
     * @apiSuccess {String} shareCode 订单产品：分享码
     * @apiSuccess {String} sharerNickName 订单产品：分享者昵称
     * @apiSuccess {String} salesCode 订单产品：分销码
     * @apiSuccess {String} resellerAcct 订单产品：分销商账号
     * @apiSuccess {String} resellerName 订单产品：分销商名称
     * @apiSuccess {String} channel 订单产品：渠道
     * @apiSuccess {String} channelName 订单产品：分销商名称
     * @apiSuccess {String} sellPath 订单产品：销售路径
     * @apiSuccess {String} extStoreId 订单产品：分销产品门店信息
     * @apiSuccess {Long} couponId 订单产品：优惠券id
     *
     * @apiSuccessExample {json} 待付款，已取消，不拆单:
     * {
     *  "code": "1",
     *  "desc": "成功",
     *  "data": {
     *          "data": [
     *                      {
     *                          "id": 2829,
     *                          "dateCreated": "2016-11-11 19:25:19",
     *                          "lastUpdated": "2016-11-11 11:04:39",
     *                          "mallId": 1,
     *                          "totalAmount": 96,
     *                          "discountTotalAmount": 96,
     *                          "oriTotalAmount": 100,
     *                          "orderNum": "201611111104118363310268",
     *                          "shoppingMan": "dsagds",
     *                          "shoppingManPhone": "18646352341",
     *                          "status": "CANCEL",
     *                          "customerId": 93,
     *                          "marketServiceRate": 0,
     *                          "actualPrice": 0,
     *                          "platformServiceFeeRates": "2.5",
     *                          "merchantOrderItemList": [
     *                                                      {
     *                                                          "id": 3738,
     *                                                          "dateCreated": "2016-11-11 11:04:39",
     *                                                          "lastUpdated": "2016-11-11 11:04:39",
     *                                                          "version": 0,
     *                                                          "merchantOrderId": 3555,
     *                                                          "merchantId": 1,
     *                                                          "productId": 502,
     *                                                          "productName": "它的分类是护肤品",
     *                                                          "logoUrl": "/20160927/20160927164018aBtkRUX3.jpg",
     *                                                          "productDateDisabled": "2017-09-27 00:00:00",
     *                                                          "productRefundable": "YES",
     *                                                          "resellFee": 2.36,
     *                                                          "shareFee": 2.12,
     *                                                          "serveRate": "2.5",
     *                                                          "shareRate": "50",
     *                                                          "singleAmount": 48,
     *                                                          "buyCount": 2,
     *                                                          "totalAmount": 96,
     *                                                          "mallId": 1,
     *                                                          "mallOrderNum": "201611111104118363310268",
     *                                                          "sellPath": "UNKNOWN"
     *                                                      },
     *                                                      ...
     *                                                  ]
     *                      },
     *                      ...
     *                  ],
     *                  "totalCount": 30,
     *                  "totalPage": 3,
     *                  "pageNo": 0,
     *                  "pageSize": 10
     *          }
     *  }
     *
     */
    @RequestMapping(value = Routes.ORDER_LIST, method = RequestMethod.GET)
    public JsonResult list(Integer pageNo, Integer pageSize, String status, String evaluateStatus, HttpServletRequest request) {
        CustomerDto customerDto = customerHelper.getSession(request);
        RestDoing doing = jsonResult -> {
            if (pageNo == null || pageNo == null) {
                jsonResult.remind("请输入分页条件",log);
                return;
            }
            //订单状态不能为空，ALL时查所有
            if (StringUtils.isBlank(status) || (!"OVERDUE".equals(status) && !EnumUtils.isValidEnum(OrderStatus.class, status))) {
                jsonResult.errorParam("请正确输入订单状态",log);
                return;
            }
            if (StringUtils.isBlank(evaluateStatus) || !EnumUtils.isValidEnum(EvaluateStatus.class, evaluateStatus)) {
                jsonResult.errorParam("请正确输入评价状态",log);
                return;
            }
            //待付款、待发货、待收货、待自提、待使用、待评价、已完成、已过期、已取消
            OrderStatus orderStatus1 = OrderStatus.valueOf(status);
            if (!"OVERDUE".equals(status) && (OrderStatus.WAIT_PAYING == orderStatus1 || OrderStatus.CANCEL == orderStatus1)) {
                //待付款，已取消，不拆单
                List<String> orderStatus = new ArrayList();
                if (OrderStatus.WAIT_PAYING == orderStatus1) {
                    orderStatus.add(MallOrderStatus.WAIT_PAYING.toString());
                }
                if (OrderStatus.CANCEL == orderStatus1) {
                    orderStatus.add(MallOrderStatus.CANCEL.toString());
                }
                //查询订单mallOrder
                PageResult<MallOrderDto> MallOrderDtoPage = mallOrderRepository.findByCustomerIdAndStatusInPage(customerDto.getId(), orderStatus, this.getPage(pageNo, pageSize));
                List<String> mallOrderNumList = MallOrderDtoPage.data.stream().map(MallOrderDto::getOrderNum).collect(Collectors.toList());
                //查询merchantOrder订单
                List<MerchantOrder> merchantOrderList = merchantOrderRepository.findByMallOrderNumInAndIsDeleteAndMerchantRoleNot(mallOrderNumList, Whether.NO, MerchantOrderMerchantRole.SUPPLIER);
                List<String> merchantOrderNumList = merchantOrderList.stream().map(MerchantOrder::getOrderNum).collect(Collectors.toList());
                //一次查完所有商品，减少IO
                List<MerchantOrderItem> merchantOrderItemList = merchantOrderItemRepository.findByMerchantOrderNumIn(merchantOrderNumList);
                //分组
                Map<String, List<MerchantOrderItem>> merchantOrderItemMap = merchantOrderItemList.stream().collect(Collectors.groupingBy(MerchantOrderItem::getMallOrderNum));
                //装载订单商品
                MallOrderDtoPage.data.stream().forEach(mallOrderDto -> {
                    mallOrderDto.setMerchantOrderItemList(merchantOrderItemMap.get(mallOrderDto.getOrderNum()));
                });
                jsonResult.setData(MallOrderDtoPage);
            } else {
                //orderType GOODS(待发货、待备货/待收货/待自提)、SERVICE(待使用/已过期), evaluateStatus 待评价、status已完成，拆单
                String orderType = OrderType.GOODS.toString();
                if ("OVERDUE".equals(status) || OrderStatus.WAIT_USE == orderStatus1) {
                    orderType = OrderType.SERVICE.toString();
                } else if (EvaluateStatus.WAIT_EVALUATE == EvaluateStatus.valueOf(evaluateStatus) || OrderStatus.FINISHED == orderStatus1) {
                    orderType = OrderType.ALL.toString();
                } else if (EvaluateStatus.DEFAULT == EvaluateStatus.valueOf(evaluateStatus) && OrderStatus.ALL == orderStatus1) {//小程序全部订单
                    orderType = OrderType.ALL.toString();
                }else if (!(OrderStatus.WAIT_SHIPPED == orderStatus1 || OrderStatus.WAIT_SHOP_PICKUP == orderStatus1 || OrderStatus.SHIPPED == orderStatus1)) {
                    jsonResult.errorParam("输入参数有误",log);
                    return;
                }
                //查询订单merchantOrder
                PageResult<MerchantOrderDto> merchantOrderDtoPage = merchantOrderRepository.findByCustomerIdPage(customerDto.getId(), orderType, status, evaluateStatus, Whether.NO, this.getPage(pageNo, pageSize));
                List<String> merchantOrderIdList = merchantOrderDtoPage.data.stream().map(MerchantOrderDto::getOrderNum).collect(Collectors.toList());
                //查询订单商品
                List<MerchantOrderItem> merchantOrderItemList = merchantOrderItemRepository.findByMerchantOrderNumIn(merchantOrderIdList);
                //分组
                Map<String, List<MerchantOrderItem>> merchantOrderItemMap = merchantOrderItemList.stream().collect(Collectors.groupingBy(MerchantOrderItem::getMerchantOrderNum));
                //装载订单商品
                merchantOrderDtoPage.data.forEach(merchantOrderDto -> {
                    merchantOrderDto.setMerchantOrderItemList(merchantOrderItemMap.get(merchantOrderDto.getOrderNum()));
                });
                jsonResult.setData(merchantOrderDtoPage);
            }
        };
        return doing.go(request, log);
    }

    /**
     * @api {get} /api/v2/order/list_statistics 订单统计（待付款，待收货，待自提，待使用,待发货）
     * @apiGroup order
     * @apiVersion 1.0.0
     *
     * @apiHeader {String} userToken 用户Token
     * @apiHeader {String} domain 平台域名
     *
     * @apiSuccess {Integer} waitPayingCount 待付款
     * @apiSuccess {Integer} waitShippedCount 待收货
     * @apiSuccess {Integer} waitShopPickupCount 待自提
     * @apiSuccess {Integer} waitUseCount 待使用
     * @apiSuccess {Integer} waitToShippedCount 待发货
     *
     * @apiSuccessExample {json} Success-Response:
     *{
     *  "code": "1",
     *  "desc": "成功",
     *  "data": {
     *              "waitPayingCount": 1,
     *              "waitShippedCount": 1,
     *              "waitShopPickupCount": 4,
     *              "waitUseCount": 1
     *          }
     *  }
     *
     */
    @RequestMapping(value = Routes.ORDER_LIST_STATISTICS, method = RequestMethod.GET)
    public JsonResult listStatistics(HttpServletRequest request) {
        CustomerDto customerDto = customerHelper.getSession(request);
        RestDoing doing = jsonResult -> {
            //待付款，不拆单
            List<MallOrderStatus> orderStatus = new ArrayList();
            orderStatus.add(MallOrderStatus.WAIT_PAYING);
            Integer waitPayingCount = mallOrderRepository.countByCustomerIdAndStatusInAndIsDelete(customerDto.getId(), orderStatus, Whether.NO);
            //待收货（status = SHIPPED,evaluateStatus = DEFAULT）
            Integer waitShippedCount = merchantOrderRepository.countByCustomerIdAndOrderTypeAndStatusAndEvaluateStatusAndIsDeleteAndMerchantRoleNot(customerDto.getId(), OrderType.GOODS, OrderStatus.SHIPPED, EvaluateStatus.DEFAULT, Whether.NO, MerchantOrderMerchantRole.SUPPLIER);
            //待自提（status = WAIT_SHOP_PICKUP,evaluateStatus = DEFAULT）
            Integer waitShopPickupCount = merchantOrderRepository.countByCustomerIdAndOrderTypeAndStatusAndEvaluateStatusAndIsDeleteAndMerchantRoleNot(customerDto.getId(), OrderType.GOODS, OrderStatus.WAIT_SHOP_PICKUP, EvaluateStatus.DEFAULT, Whether.NO, MerchantOrderMerchantRole.SUPPLIER);
            //待使用（status = WAIT_USE\PART_USE,evaluateStatus = DEFAULT）
            Integer waitUseCount = merchantOrderRepository.countWaitUseAndPartUse(customerDto.getId());

            Integer waitToShippedCount  = merchantOrderRepository.countByCustomerIdAndOrderTypeAndStatusAndEvaluateStatusAndIsDeleteAndMerchantRoleNot(customerDto.getId(), OrderType.GOODS, OrderStatus.WAIT_SHIPPED, EvaluateStatus.DEFAULT, Whether.NO, MerchantOrderMerchantRole.SUPPLIER);
            OrderStatisticsDto orderStatisticsDto = new OrderStatisticsDto();
            orderStatisticsDto.setWaitPayingCount(waitPayingCount);
            orderStatisticsDto.setWaitShippedCount(waitShippedCount);
            orderStatisticsDto.setWaitShopPickupCount(waitShopPickupCount);
            orderStatisticsDto.setWaitUseCount(waitUseCount);
            orderStatisticsDto.setWaitToShippedCount(waitToShippedCount);

            jsonResult.setData(orderStatisticsDto);

        };
        return doing.go(request, log);
    }


    /**
     * @api {get} /api/v2/order/show/{orderNum} 订单详情
     * @apiGroup order
     * @apiVersion 1.0.0
     *
     * @apiHeader {String} userToken 用户Token
     * @apiHeader {String} domain 平台域名
     *
     * @apiParam {String} orderNumLevel MERCHANT_LEVEL(商铺级,查询目标是非待付款、已取消的订单，已拆单),MALL_LEVEL(平台级，查询目标是待付款、已取消的订单，未拆单)
     * @apiParam {String} orderNum 订单号
     *
     * @apiSuccess {Long} id 商户订单ID
     * @apiSuccess {Long} version 版本
     * @apiSuccess {Date} dateCreated 创建时间
     * @apiSuccess {Date} laseUpdated 更新时间
     * @apiSuccess {String} orderNum 商户订单号
     * @apiSuccess {Long} mallOrderId 平台 订单id
     * @apiSuccess {String} mallOrderNum 平台订单号
     * @apiSuccess {Long} mallId 平台id
     * @apiSuccess {Long} customerId 客户id
     * @apiSuccess {String} customerName 客户名称
     * @apiSuccess {String} customerShareCode 客户分销码
     * @apiSuccess {Long} merchantId 商户id
     * @apiSuccess {String} merchantName 商户名称
     * @apiSuccess {Long} merchantStoreId 商户门店 id
     * @apiSuccess {BigDecimal} amount 金额
     * @apiSuccess {String} shoppingAddress 收货人地址
     * @apiSuccess {String} shoppingMan 收货人
     * @apiSuccess {String} shoppingManPhone 收货人电话号码
     * @apiSuccess {String} status 订单状态 WAIT_PAYING("待支付"), CANCEL("取消"), PAYED("已支付"), WAIT_SHIPPED("等待发货"), SHIPPED("已发货"), SHOP_PICKUP("到店自提"), PART_SHOP_PICKUP("部分到店自提"), CONFIRM_PICKUP("确认自提"), CONFIRM("已确认"), WAIT_USE("待使用"), PART_USE("部分使用"), USED("已使用"), FINISHED("已完成"), APPLY_REJECT("申请退货"), FINISHED_REJECT("已完成退货"), APPLY_REFUND("申请退款"), FINISHED_REFUND("已完成退款")
     * @apiSuccess {String} logisticsNumber 物流单号
     * @apiSuccess {Long} logisticsId 物流公司ID(其它为0)
     * @apiSuccess {String} logisticsName 物流公司名称
     * @apiSuccess {Date} dateDelivered 发货时间
     * @apiSuccess {Date} dateReceived 收货时间
     * @apiSuccess {String} remark 备注
     * @apiSuccess {String} productShoppingType 物流种类 SHOP_PICKUP("到店自提"), SHIPPING("物流")
     * @apiSuccess {String} orderType 订单类型 GOODS("实物商品"), SERVICE("到店服务")
     * @apiSuccess {String} settleStatus 结算状态 WAIT_SETTLE("待结算"), PART_SETTLE("部分结算"), SETTLED("已结算")
     * @apiSuccess {String} channelSalesCode 渠道分销码
     * @apiSuccess {String} payMethod 支付方式
     * @apiSuccess {Date} datePaid 支付时间
     * @apiSuccess {String} merchantOrderExtType 物流种类 SELF("自营订单"), MARKET("分销订单")
     * @apiSuccess {String} merchantOrderExtSourceType SOURCE("下单源"), MARKET("分销下单")
     * @apiSuccess {String} extSourceOrderId 订单分销来源id
     * @apiSuccess {String} beginDate 开始时间 yyyy-MM-dd
     * @apiSuccess {String} endDate 结束时间 yyyy-MM-dd
     * @apiSuccess {String} productType 产品类型
     * @apiSuccess {String} productSource 产品来源
     * @apiSuccess {List} merchantOrderItemList 订单所含产品
     *
     * @apiSuccess {Long} id ItemId
     * @apiSuccess {Long} version 版本
     * @apiSuccess {Date} dateCreated 创建时间
     * @apiSuccess {Date} laseUpdated 更新时间
     * @apiSuccess {Long} merchantOrderId 商家订单 id
     * @apiSuccess {Long} merchantId 商家 id
     * @apiSuccess {Long} productId 产品 id
     * @apiSuccess {String} productName 产品名称
     * @apiSuccess {String} logoUrl 产品图片
     * @apiSuccess {Date} productDateDisabled 产品过期退时间
     * @apiSuccess {String=YES("是"), NO("否")} productRefundable 是否支持过期退
     * @apiSuccess {Boolean} productRefundableIsRun 是否已执行自动退款
     * @apiSuccess {BigDecimal} resellFee 产品分销佣金
     * @apiSuccess {BigDecimal} shareFee 产品分享返利
     * @apiSuccess {String} serveRate 服务费比率
     * @apiSuccess {String} shareRate M/D分享比率
     * @apiSuccess {BigDecimal} singleAmount 产品单价
     * @apiSuccess {Long} buyCount 购买数量
     * @apiSuccess {BigDecimal} totalAmount 合计金额
     * @apiSuccess {Long} mallId 平台id
     * @apiSuccess {String} mallOrderNum 平台订单号
     * @apiSuccess {Long} merchantStoreId 关联门店id
     * @apiSuccess {String} shareCode 分享码
     * @apiSuccess {String} sharerId 分享者id
     * @apiSuccess {String} sharerNickName 分享者昵称
     * @apiSuccess {String} salesCode 分销码
     * @apiSuccess {String} resellerAcct 分销商账号
     * @apiSuccess {String} resellerName 分销商名称
     * @apiSuccess {String} channel 渠道
     * @apiSuccess {String} channelName 渠道名称
     * @apiSuccess {String} sellPath 销售路径
     * @apiSuccess {String} extStoreId 分销产品门店信息
     * @apiSuccess {String} couponId 优惠券id
     *
     * @apiSuccessExample {json} MALL_LEVEL(平台级，查询目标是待付款、已取消的订单，未拆单):
     *{
     *  "code": "1",
     *  "desc": "成功",
     *  "data": {
     *          "id": 3663,
     *          "dateCreated": "2016-11-15 20:17:11",
     *          "lastUpdated": "2016-11-15 20:17:11",
     *          "orderNum": "201611152017151671594364",
     *          "mallOrderId": 2902,
     *          "mallOrderNum": "201611152017151494996936",
     *          "mallId": 1,
     *          "customerId": 93,
     *          "customerName": "小周子",
     *          "merchantId": 2,
     *          "merchantName": "歌力思",
     *          "amount": 20,
     *          "address": "23we",
     *          "shoppingMan": "111",
     *          "shoppingManPhone": "13245678767",
     *          "status": "WAIT_PAYING",
     *          "remark": "",
     *          "productShoppingType": "SHIPPING",
     *          "orderType": "GOODS",
     *          "settleStatus": "WAIT_SETTLE",
     *          "sourceType": "SELF",
     *          "merchantOrderItemList": [
     *                                      {
     *                                          "id": 3879,
     *                                          "dateCreated": "2016-11-15 20:17:11",
     *                                          "lastUpdated": "2016-11-15 20:17:11",
     *                                          "version": 0,
     *                                          "merchantOrderId": 3663,
     *                                          "merchantId": 2,
     *                                          "productId": 969,
     *                                          "productName": "湘天华纯天然茶籽粉洗洁袋",
     *                                          "logoUrl": "http://uploads.rockcent.com//uat/product/face/201611/1015572479535ebe073-ae69-4655-8e5a-d47a0498ac631.jpg",
     *                                          "productRefundable": false,
     *                                          "resellFee": 5,
     *                                          "shareFee": 5,
     *                                          "serveRate": "2.5",
     *                                          "shareRate": "50",
     *                                          "singleAmount": 20,
     *                                          "buyCount": 1,
     *                                          "totalAmount": 20,
     *                                          "mallId": 1,
     *                                          "mallOrderNum": "201611152017151494996936",
     *                                          "sellPath": "UNKNOWN",
     *                                          "couponId": 185
     *                                      },
     *                                      ...
     *                                  ]
     *          }
     *  }
     *
     * @apiSuccessExample {json} MERCHANT_LEVEL(商铺级,查询目标是非待付款、已取消的订单，已拆单):
     * {
     *  "code": "1",
     *  "desc": "成功",
     *  "data": {
     *          "id": 3663,
     *          "dateCreated": "2016-11-15 20:17:11",
     *          "lastUpdated": "2016-11-15 20:17:11",
     *          "orderNum": "201611152017151671594364",
     *          "mallOrderId": 2902,
     *          "mallOrderNum": "201611152017151494996936",
     *          "mallId": 1,
     *          "customerId": 93,
     *          "customerName": "小周子",
     *          "merchantId": 2,
     *          "merchantName": "歌力思",
     *          "amount": 20,
     *          "address": "23we",
     *          "shoppingMan": "111",
     *          "shoppingManPhone": "13245678767",
     *          "status": "WAIT_PAYING",
     *          "remark": "",
     *          "productShoppingType": "SHIPPING",
     *          "orderType": "GOODS",
     *          "settleStatus": "WAIT_SETTLE",
     *          "sourceType": "SELF",
     *          "merchantOrderItemList": [
     *                                      {
     *                                          "id": 3879,
     *                                          "dateCreated": "2016-11-15 20:17:11",
     *                                          "lastUpdated": "2016-11-15 20:17:11",
     *                                          "version": 0,
     *                                          "merchantOrderId": 3663,
     *                                          "merchantId": 2,
     *                                          "productId": 969,
     *                                          "productName": "湘天华纯天然茶籽粉洗洁袋",
     *                                          "logoUrl": "http://uploads.rockcent.com//uat/product/face/201611/1015572479535ebe073-ae69-4655-8e5a-d47a0498ac631.jpg",
     *                                          "productRefundable": false,
     *                                          "resellFee": 5,
     *                                          "shareFee": 5,
     *                                          "serveRate": "2.5",
     *                                          "shareRate": "50",
     *                                          "singleAmount": 20,
     *                                          "buyCount": 1,
     *                                          "totalAmount": 20,
     *                                          "mallId": 1,
     *                                          "mallOrderNum": "201611152017151494996936",
     *                                          "sellPath": "UNKNOWN",
     *                                          "couponId": 185
     *                                      }，
     *                                      ...
     *                                  ]
     *          }
     *  }
     *
     */
    @RequestMapping(value = Routes.ORDER_SHOW, method = RequestMethod.GET)
    public JsonResult show(String orderNumLevel, @PathVariable String orderNum, HttpServletRequest request) {
        CustomerDto customerDto = customerHelper.getSession(request);
        RestDoing doing = jsonResult -> {
            if (StringUtils.isBlank(orderNum) || StringUtils.isBlank(orderNumLevel)) {
                jsonResult.remind("查询条件不能为空",log);
                return;
            }

            if ("MERCHANT_LEVEL".equals(orderNumLevel)) {
                //查询的是拆单后的订单
                MerchantOrderDto merchantOrderDto = new MerchantOrderDto();
                //查merchantOrder
                MerchantOrder merchantOrder = merchantOrderRepository.findByOrderNumAndMallId(orderNum, customerDto.getMallId());
                if (merchantOrder == null || !merchantOrder.getMallId().equals(customerDto.getMallId())) {
                    jsonResult.errorParam("订单不存在",log);
                    return;
                }
                //取其中的订单信息
                RBeanUtils.copyProperties(merchantOrder, merchantOrderDto);
                //枚举类型的
                merchantOrderDto.setStatus(merchantOrder.getStatus().toString());
                merchantOrderDto.setOrderType(merchantOrder.getOrderType().toString());
                merchantOrderDto.setSourceType(merchantOrder.getSourceType().toString());
                merchantOrderDto.setEvaluateStatus(merchantOrder.getEvaluateStatus().toString());
                merchantOrderDto.setPaymentMethod(merchantOrder.getPaymentMethod().toString());
                //类型名称不同的
                merchantOrderDto.setAddress(merchantOrder.getShoppingAddress());
                merchantOrderDto.setProductShoppingType(merchantOrder.getProductShoppingType().toString());
                //查订单Item
                List<MerchantOrderItem> merchantOrderItemList = merchantOrderItemRepository.findByMerchantOrderId(merchantOrder.getId());
                merchantOrderDto.setMerchantOrderItemList(merchantOrderItemList);

                Long packageId = merchantOrder.getGiftPacketId();

                if(null!=packageId){
                    MerchantGiftPacket giftPacket = merchantGiftPacketRepository.findOne(packageId);

                    MallFinancialSettings mallFinancialSettings = mallFinancialSettingsRepository.findTop1ByMallIdAndIsDeleteOrderByLastUpdatedDesc(customerDto.getMallId(), Whether.NO);
                    BigDecimal shareRate = mallFinancialSettings.getShareFeeRate() == null ? BigDecimal.valueOf(0): mallFinancialSettings.getShareFeeRate();
                    BigDecimal shareFeeRates = BigDecimalUtils.divide(shareRate, "100");
//                    log.info("----------------------->mallFinancialSettings:{}",mallFinancialSettings);
//                    log.info("----------------------->shareFeeRates:{}",shareFeeRates);
//                    log.info("----------------------->giftPacket.getShareFee():{}",giftPacket.getShareFee());
                    BigDecimal shareFee = giftPacket.getShareFee().multiply(shareFeeRates);
//                    log.info("----------------------->shareFee:{}",shareFee);

                    merchantOrderDto.setShareFee(shareFee);
//                    log.info("----------------------->shareRate:{}",merchantOrderDto.getShareFee());
                }
//                log.info("----------------------->merchantOrderDto:{}",merchantOrderDto);

                jsonResult.setData(merchantOrderDto);
            } else if ("MALL_LEVEL".equals(orderNumLevel)) {
                //查询未拆单的订单（未付款，已取消）
                MallOrderDto mallOrderDto = new MallOrderDto();
                MallOrder mallorder = mallOrderRepository.findByOrderNumAndMallId(orderNum, customerDto.getMallId());
                if (mallorder == null) {
                    jsonResult.errorParam("订单不存在",log);
                    return;
                }
                RBeanUtils.copyProperties(mallorder, mallOrderDto);
                //查所有merchantOrder / 拆单时merchantOrder有多个，根据merchantOrderNum查为了检查商品类型
                List<MerchantOrder> merchantOrderList = merchantOrderRepository.findByMallOrderNumAndIsDeleteAndMerchantRoleNot(orderNum, Whether.NO, MerchantOrderMerchantRole.SUPPLIER);
                //检查订单发货方式
                List<ProductShippingType> shippingType = merchantOrderList.stream().map(MerchantOrder::getProductShoppingType).collect(Collectors.toList());
                if (shippingType.contains(ProductShippingType.SHIPPING) && shippingType.contains(ProductShippingType.SHOP_PICKUP)) {
                    mallOrderDto.setProductShoppingType(ProductShippingType.SHOP_PICKUP_AND_SHIPPING.toString());
                } else if (shippingType.contains(ProductShippingType.SHIPPING)) {
                    mallOrderDto.setProductShoppingType(ProductShippingType.SHIPPING.toString());
                } else if (shippingType.contains(ProductShippingType.SHOP_PICKUP)) {
                    mallOrderDto.setProductShoppingType(ProductShippingType.SHOP_PICKUP.toString());
                }
                Map<String, List<MerchantOrder>> merchantOrderMap = merchantOrderList.stream().collect(Collectors.groupingBy(MerchantOrder::getOrderNum));
                //拆单时merchantOrder有多个
                List<String> merchantOrderNumList = merchantOrderList.stream().map(MerchantOrder::getOrderNum).collect(Collectors.toList());
                List<MerchantOrderItem> merchantOrderItemList = merchantOrderItemRepository.findByMerchantOrderNumInAndIsDelete(merchantOrderNumList, Whether.NO);
                List<MerchantOrderItemDto> merchantOrderItemDtoList = merchantOrderItemList.stream().map(merchantOrderItem -> {
                    MerchantOrderItemDto merchantOrderItemDto = new MerchantOrderItemDto();
                    RBeanUtils.copyProperties(merchantOrderItem, merchantOrderItemDto);
                    //商品类型
                    merchantOrderItemDto.setType(merchantOrderMap.get(merchantOrderItem.getMerchantOrderNum()).get(0).getOrderType().toString());
                    //商品的配送方式
                    merchantOrderItemDto.setShoppingType(merchantOrderMap.get(merchantOrderItem.getMerchantOrderNum()).get(0).getProductShoppingType().toString());
                    return merchantOrderItemDto;
                }).collect(Collectors.toList());
                mallOrderDto.setProductList(merchantOrderItemDtoList);
                Long packageId = mallorder.getGiftId();

                if(null!=packageId){
                    MerchantGiftPacket giftPacket = merchantGiftPacketRepository.findOne(packageId);

                    MallFinancialSettings mallFinancialSettings = mallFinancialSettingsRepository.findTop1ByMallIdAndIsDeleteOrderByLastUpdatedDesc(customerDto.getMallId(), Whether.NO);
                    BigDecimal shareRate = mallFinancialSettings.getShareFeeRate() == null ? BigDecimal.valueOf(0): mallFinancialSettings.getShareFeeRate();
                    BigDecimal shareFeeRates = BigDecimalUtils.divide(shareRate, "100");
//                    log.info("----------------------->mallFinancialSettings:{}",mallFinancialSettings);
//                    log.info("----------------------->shareFeeRates:{}",shareFeeRates);
//                    log.info("----------------------->giftPacket.getShareFee():{}",giftPacket.getShareFee());
                    BigDecimal shareFee = giftPacket.getShareFee().multiply(shareFeeRates);
//                    log.info("----------------------->shareFee:{}",shareFee);

                    mallOrderDto.setShareFee(shareFee);
//                    log.info("----------------------->shareRate:{}",mallOrderDto.getShareFee());

                }
//                log.info("----------------------->mallOrderDto:{}",mallOrderDto);
                jsonResult.setData(mallOrderDto);
            } else {
                jsonResult.errorParam("orderNumLevel 参数错误",log);
                return;
            }
        };
        return doing.go(request, log);
    }

    /**
     * @api {get} /api/v2/order/my_products 我的宝贝（我购买到的产品）
     * @apiGroup order
     * @apiVersion 1.0.0
     *
     * @apiHeader {String} userToken 用户Token
     * @apiHeader {String} domain 平台域名
     *
     * @apiParam {Integer} pageNo 页码
     * @apiParam {Integer} pageSize 页记录数
     * @apiParam {Boolean} isGift 是否礼包，true：查礼包，false：查产品
     *
     * @apiSuccess {Long} id 订单ID
     * @apiSuccess {Long} version 版本
     * @apiSuccess {Date} dateCreated 创建时间
     * @apiSuccess {Date} laseUpdated 更新时间
     * @apiSuccess {String} orderNum 订单号
     * @apiSuccess {Long} mallOrderId 平台 订单id
     * @apiSuccess {String} mallOrderNum 平台订单号
     * @apiSuccess {Long} mallId 平台id
     * @apiSuccess {Long} customerId 客户id
     * @apiSuccess {String} customerName 客户名称
     * @apiSuccess {String} customerShareCode 客户分销码
     * @apiSuccess {String} merchantId 商户id
     * @apiSuccess {String} merchantName 商户名称
     * @apiSuccess {String} status 订单状态 WAIT_PAYING(\"待支付\"), CANCEL(\"取消\"), PAYED(\"已支付\"), WAIT_SHIPPED(\"等待发货\"), SHIPPED(\"已发货\"), SHOP_PICKUP(\"到店自提\"), PART_SHOP_PICKUP(\"部分到店自提\"), CONFIRM_PICKUP(\"确认自提\"), CONFIRM(\"已确认\"), WAIT_USE(\"待使用\"), PART_USE(\"部分使用\"), USED(\"已使用\"), FINISHED(\"已完成\"), APPLY_REJECT(\"申请退货\"), FINISHED_REJECT(\"已完成退货\"), APPLY_REFUND(\"申请退款\"), FINISHED_REFUND(\"已完成退款\")
     * @apiSuccess {String} orderType 订单类型 GOODS(\"实物商品\"), SERVICE(\"到店服务\")
     * @apiSuccess {Long} merchantStoreId 商户门店 id
     * @apiSuccess {BigDecimal} amount 金额
     * @apiSuccess {String} shoppingAddress 收货人地址
     * @apiSuccess {String} shoppingMan 收货人
     * @apiSuccess {String} shoppingManPhone 收货人电话号码
     * @apiSuccess {String} logisticsNumber 物流单号
     * @apiSuccess {Long} logisticsId 物流公司ID(其它为0)
     * @apiSuccess {String} logisticsName 物流公司名称
     * @apiSuccess {Date} dateDelivered 发货时间
     * @apiSuccess {Date} dateReceived 收货时间
     * @apiSuccess {String} remark 支付URL
     * @apiSuccess {Long} productShoppingType 物流种类 SHOP_PICKUP("到店自提"), SHIPPING("物流")
     * @apiSuccess {String} settleStatus 结算状态 WAIT_SETTLE("待结算"), PART_SETTLE("部分结算"), SETTLED("已结算")
     * @apiSuccess {String} channelSalesCode 渠道分销码
     * @apiSuccess {String} payMethod 支付方式
     * @apiSuccess {Date} datePaid 支付时间
     * @apiSuccess {String} merchantOrderExtType 物流种类 SELF("自营订单"), MARKET("分销订单")
     * @apiSuccess {String} merchantOrderExtSourceType SOURCE("下单源"), MARKET("分销下单")
     * @apiSuccess {String} datePaid extSourceOrderId 订单分销来源id
     * @apiSuccess {List} merchantOrderItemList 购买的产品
     *
     * @apiSuccess {Long} merchantOrderId 订单产品：商家订单 id
     * @apiSuccess {Long} merchantId 订单产品：商家 id
     * @apiSuccess {Long} productId 订单产品：产品 id
     * @apiSuccess {String} productName 订单产品：产品名称
     * @apiSuccess {String} logoUrl 订单产品：产品图片
     * @apiSuccess {Date} productDateDisabled 订单产品：产品过期退时间
     * @apiSuccess {String=YES("是"), NO("否")} productRefundable 订单产品：是否支持过期退
     * @apiSuccess {Boolean} productRefundableIsRun 订单产品：是否已执行自动退款
     * @apiSuccess {BigDecimal} resellFee 订单产品：产品分销佣金
     * @apiSuccess {BigDecimal} shareFee 订单产品：产品分享返利
     * @apiSuccess {String} serveRate 订单产品：服务费比率
     * @apiSuccess {String} shareRate 订单产品：M/D分享比率
     * @apiSuccess {BigDecimal} singleAmount 订单产品：产品单价
     * @apiSuccess {Long} buyCount 订单产品：购买数量
     * @apiSuccess {BigDecimal} totalAmount 订单产品：合计金额
     * @apiSuccess {Long} mallId 订单产品：平台id
     * @apiSuccess {String} mallOrderNum 订单产品：平台订单号
     * @apiSuccess {Long} merchantStoreId 订单产品：关联门店id
     * @apiSuccess {String} shareCode 订单产品：分享码
     * @apiSuccess {String} sharerNickName 订单产品：分享者昵称
     * @apiSuccess {String} salesCode 订单产品：分销码
     * @apiSuccess {String} resellerAcct 订单产品：分销商账号
     * @apiSuccess {String} resellerName 订单产品：分销商名称
     * @apiSuccess {String} channel 订单产品：渠道
     * @apiSuccess {String} channelName 订单产品：分销商名称
     * @apiSuccess {String} sellPath 订单产品：销售路径
     * @apiSuccess {String} extStoreId 订单产品：分销产品门店信息
     * @apiSuccess {Long} couponId 订单产品：优惠券id
     *
     * @apiSuccess {String} couponId 优惠券id
     *
     * @apiSuccessExample {json} 商品:
     * {
     *  "code": "1",
     *  "desc": "成功",
     *  "data": {
     *          "data": [
     *                      {
     *                          "id": 3218,
     *                          "dateCreated": "2016-08-22 18:05:30",
     *                          "lastUpdated": "2016-08-22 18:05:30",
     *                          "orderNum": "1608220112573",
     *                          "mallId": 1,
     *                          "customerId": 93,
     *                          "customerName": "胖墩",
     *                          "merchantId": 5,
     *                          "merchantName": "商城2",
     *                          "amount": 100,
     *                          "shoppingMan": "这些快递都是我的",
     *                          "shoppingManPhone": "13235223",
     *                          "status": "CANCEL",
     *                          "orderType": "GOODS",
     *                          "settleStatus": "WAIT_SETTLE",
     *                          "merchantOrderExtType": "MARKET",
     *                          "merchantOrderExtSourceType": "SOURCE",
     *                          "merchantOrderItemList": [
     *                                                      {
     *                                                          "id": 3406,
     *                                                          "dateCreated": "2016-10-11 11:29:53",
     *                                                          "lastUpdated": "2016-10-11 11:29:53",
     *                                                          "version": 0,
     *                                                          "merchantOrderId": 3218,
     *                                                          "productId": 124,
     *                                                          "productName": "BDC的商品",
     *                                                          "logoUrl": "http://upload.uat.rockcent.com/images/20160614/201606141848279Le0jj0J.jpg",
     *                                                          "productRefundable": false,
     *                                                          "productRefundableIsRun": false,
     *                                                          "resellFee": 5,
     *                                                          "shareFee": 2,
     *                                                          "serveRate": "2.5",
     *                                                          "singleAmount": 100,
     *                                                          "buyCount": 1,
     *                                                          "totalAmount": 100,
     *                                                          "mallOrderNum": "1608220112573",
     *                                                          "channel": "12",
     *                                                          "channelName": "默认自有渠道",
     *                                                          "sellPath": "B2D2C"
     *                                                      },
     *                                                      ...
     *                                                  ]
     *                      },
     *                      ...
     *                  ],
     *                  "totalCount": 65,
     *                  "totalPage": 7,
     *                  "pageNo": 0,
     *                  "pageSize": 10
     *          }
     *  }
     * @apiSuccessExample {json} 礼包:
     * {
     *  "code": "1",
     *  "desc": "成功",
     *  "data": {
     *          "data": [
     *                      {
     *                          "id": 132,
     *                          "dateCreated": "2016-08-30 15:03:51",
     *                          "lastUpdated": "2016-09-29 00:02:56",
     *                          "name": "女装礼包",
     *                          "coverUrl": "/20160830/20160830144934Ou6xsdWp.jpg",
     *                          "dateEnabled": "2016-08-30 00:00:00",
     *                          "dateDisabled": "2016-09-29 00:00:00",
     *                          "intro": "礼包简介",
     *                          "shareFee": 5,
     *                          "basePrice": 694,
     *                          "sellPrice": 688,
     *                          "status": "S5_FINISHED",
     *                          "merchantId": 74,
     *                          "merchantName": "一二三",
     *                          "resellFee": 21,
     *                          "giftNum": 1
     *                      },
     *                       ...
     *                  ],
     *                  "totalCount": 3,
     *                  "totalPage": 1,
     *                  "pageNo": 0,
     *                  "pageSize": 10
     *           }
     *  }
     *
     */
    @RequestMapping(value = Routes.ORDER_MY_PRODUCTS, method = RequestMethod.GET)
    //public JsonResult myProducts(Integer pageNo, Integer pageSize, Boolean isGift, HttpServletRequest request) {
    public JsonResult myProducts(Integer pageNo, Integer pageSize,HttpServletRequest request) {
        CustomerDto customerDto = customerHelper.getSession(request);
        RestDoing doing = jsonResult -> {
            if (pageNo == null || pageSize == null) {
                jsonResult.remind("请输入分页条件",log);
                return;
            }
            //朋友价
            MallFinancialSettings mallFinancialSettings = mallFinancialSettingsRepository.findTop1ByMallIdAndIsDeleteOrderByLastUpdatedDesc(customerDto.getMallId(), Whether.NO);
            BigDecimal shareRate = mallFinancialSettings.getShareFeeRate() == null ? BigDecimal.valueOf(0): mallFinancialSettings.getShareFeeRate();
//            BigDecimal shareFeeRates = BigDecimalUtils.divide(BigDecimal.valueOf(100-shareRate.doubleValue()), "100");

            //查询用户已经买单的订单，除了取消和待付款的订单，isGift为空或false时查非礼包的，为true时查礼包
            //if (isGift != null && true == isGift) {
                List<String> orderStatusList = new ArrayList();
                orderStatusList.add(MallOrderStatus.CANCEL.toString());
                orderStatusList.add(MallOrderStatus.WAIT_PAYING.toString());
//                orderStatusList.add(MallOrderStatus.FINISHED.toString());
                PageResult<MallOrderDto> mallOrderPage = mallOrderRepository.findByCustomerIdAndStatusNotIn(customerDto.getId(), orderStatusList, true, this.getPage(pageNo, pageSize));//isGift ==true
                //如果是礼包的，直接查礼包信息
                List<MerchantGiftPacketDto> merchantGiftPacketList = mallOrderPage.data.stream().map(mallOrderDto -> {
                    MerchantGiftPacket merchantGiftPacket = merchantGiftPacketRepository.findOne(mallOrderDto.getGiftId());
                    MerchantGiftPacketDto merchantGiftPacketDto = new MerchantGiftPacketDto();
                    RBeanUtils.copyProperties(merchantGiftPacket, merchantGiftPacketDto);
                    //补充礼包个数
                    merchantGiftPacketDto.setGiftNum(mallOrderDto.getGiftNum());
                    //补充用户购买时间
                    merchantGiftPacketDto.setUserBuyDate(mallOrderDto.getDateCreated().toString());
                    //补充商城名称
                    merchantGiftPacketDto.setMerchantName(merchantRepository.findOne(merchantGiftPacket.getMerchantId()).getName());
//                    merchantGiftPacketDto.setFriendPrice((merchantGiftPacketDto.getSellPrice().subtract(merchantGiftPacketDto.getShareFee())).multiply(shareFeeRates));
                    merchantGiftPacketDto.setShareRate(shareRate);
                    return merchantGiftPacketDto;
                }).filter(merchantGiftPacketDto -> merchantGiftPacketDto.getShareFee().longValue()>0L).collect(Collectors.toList());
                PageResult giftPacketPage = new PageResult(pageNo, pageSize);
                giftPacketPage.data = merchantGiftPacketList;
                giftPacketPage.totalPage = mallOrderPage.totalPage;
                giftPacketPage.totalCount = mallOrderPage.totalCount;
               // jsonResult.setData(giftPacketPage);
           // } else {
//                orderStatusList.add(MallOrderStatus.FINISHED.toString());
                PageResult<MerchantOrderDto> merchantOrderDtoList = merchantOrderRepository.findByCustomerIdAndStatusNotIn(customerDto.getId(), orderStatusList, this.getPage(pageNo, pageSize));
                List<Long> merchantOrderIdList = merchantOrderDtoList.data.stream().map(MerchantOrderDto::getId).collect(Collectors.toList());
                List<MerchantOrderItem> merchantOrderItemList = merchantOrderItemRepository.findByMerchantOrderIdIn(merchantOrderIdList);
                Map<Long, List<MerchantOrderItem>> merchantOrderItemMap = merchantOrderItemList.stream().collect(Collectors.groupingBy(MerchantOrderItem::getMerchantOrderId));
                merchantOrderDtoList.data.stream().forEach(merchantOrderDto -> {
//
                    List<MerchantOrderItem> merchantOrderItemList2 = merchantOrderItemMap.get(merchantOrderDto.getId());
//                    log.info("-----1--------->merchantOrderItemList2:{}",merchantOrderItemList2);
                    merchantOrderItemList2 = merchantOrderItemList2.stream().filter(merchantOrderItem -> merchantOrderItem.getShareFee().longValue() > 0L).collect(Collectors.toList());
//                    log.info("-----2--------->merchantOrderItemList2:{}",merchantOrderItemList2);

                    //查询订单下的Item
                    merchantOrderDto.setMerchantOrderItemList(merchantOrderItemList2);
                });

                List<Object>  myProducts = sortProductsAndGiftsByCreatedDate(merchantOrderDtoList.data,merchantGiftPacketList);
                PageResult<Object> myProductsPage = new PageResult<Object>();
                myProductsPage.data = myProducts;
                myProductsPage.totalPage = mallOrderPage.totalPage + merchantOrderDtoList.totalPage;
                myProductsPage.totalCount = mallOrderPage.totalCount + merchantOrderDtoList.totalCount;
                jsonResult.setData(myProductsPage);
                //jsonResult.setData(merchantOrderDtoList);

           //1 }
        };
        return doing.go(request, log);
    }

    private List<Object> sortProductsAndGiftsByCreatedDate(List<MerchantOrderDto>merchantOrderDtoList,List<MerchantGiftPacketDto>merchantGiftPacketList){

        List<Object> rtList = new ArrayList<Object>();

       TreeMap<String,Object> rtMap =new TreeMap<String,Object>();
        for(MerchantOrderDto merchantOrderDto:merchantOrderDtoList){
            rtMap.put(merchantOrderDto.getDateCreated().toString(),merchantOrderDto);
        }
        for(MerchantGiftPacketDto merchantGiftPacket:merchantGiftPacketList){
            rtMap.put(merchantGiftPacket.getUserBuyDate(),merchantGiftPacket);
        }
        Iterator<java.util.Map.Entry<String,Object>> ite =  rtMap.entrySet().iterator();
        while (ite.hasNext()) {
            rtList.add(ite.next().getValue());
        }
        //将List倒序变成时间降序排序
        Collections.reverse(rtList);
        return rtList;
    }

    /**
     * @api {put} /api/v2/order/confirm/take/goods 确认收货
     * @apiGroup order
     *
     * @apiHeader {String} domain <code>必须参数</code>对应平台C端域名
     * @apiHeader {String} userToken <code>必须参数</code>用户Token
     *
     * @apiParam {String} merchantOrderNum 商家订单号
     *
     * @apiSuccessExample {json} Success-Response:
     *      {
     *      "code": 1,
     *      "desc" : "成功"
     *      }
     */
    @Transactional
    @RequestMapping(value = Routes.ORDER_CONFIRM_TAKE_GOODS, method = RequestMethod.PUT)
    public JsonResult confirmTakeGoods(HttpServletRequest request, @RequestBody MerchantOrderItem dto) {
        CustomerDto customerDto = customerHelper.getSession(request);
        RestDoing doing = jsonResult -> {
            String dtoMerchantOrderNum = dto.getMerchantOrderNum();
            if (StringUtils.isBlank(dtoMerchantOrderNum)) {
                jsonResult.remind("商家订单号 不能为空",log);
                return;
            }


            Long customerDtoMallId = customerDto.getMallId();
            MerchantOrder merchantOrder = merchantOrderRepository.findByOrderNumAndMallId(dtoMerchantOrderNum, customerDtoMallId);
            if (merchantOrder == null) {
                jsonResult.remind(MerchantOrder.REMIND_RECORD_IS_NOT_EXIST,log);
                return;
            }

            String marketOrderNum = merchantOrder.getMarketOrderNum();
            MerchantOrderMerchantRole merchantRole = merchantOrder.getMerchantRole();
            if (MerchantOrderMerchantRole.DISTRIBUTOR == merchantRole) {
                merchantOrder = merchantOrderRepository.findByMarketOrderNumAndMerchantRoleAndSourceType(marketOrderNum, MerchantOrderMerchantRole.SUPPLIER, MerchantOrderSourceType.MARKET);
            }
            if (OrderStatus.SHIPPED != merchantOrder.getStatus()) {
                jsonResult.remind("订单状态有误,请咨询客服人员",log);
                return;
            }

            if (SettlementStatus.SETTLED == merchantOrder.getSettleStatus()) {
                jsonResult.remind("订单状态有误,请咨询客服人员",log);
                return;
            }

            ProductShippingType productShoppingType = merchantOrder.getProductShoppingType();
            OrderType orderType = merchantOrder.getOrderType();
            if (OrderType.SERVICE == orderType || ProductShippingType.SHOP_PICKUP == productShoppingType) {
                jsonResult.remind("此订单属于到店服务",log);
                return;
            }

            String mallOrderNum = merchantOrder.getMallOrderNum();
            Long merchantOrderId = merchantOrder.getId();
            String merchantName = merchantOrder.getMerchantName();

            MallOrder mallOrder = mallOrderRepository.findByOrderNumAndMallId(mallOrderNum, customerDtoMallId);

            //商品确认收货订单核销结算
            Long customerDtoId = customerDto.getId();
            if (OrderType.GOODS == orderType && ProductShippingType.SHIPPING == productShoppingType) {

                List<MerchantOrderItem> orderItemList = merchantOrderItemRepository.findByMerchantOrderId(merchantOrderId);
                for (MerchantOrderItem orderItem : orderItemList) {
                    //记录核销记录
                    Long orderItemBuyCount = orderItem.getBuyCount();
                    String orderItemLogoUrl = orderItem.getLogoUrl();
                    MerchantOrderMerchantRole orderItemMerchantRole = orderItem.getMerchantRole();
                    MerchantOrderVerification orderVerification = verificationHelper.merchantOrderVerificationSave(merchantOrder, orderItem, orderItemBuyCount, null, customerDtoId, orderItemLogoUrl, merchantName, OrderVerificationWay.SELF_CONFIRM, merchantRole);
                    merchantOrderVerificationRepository.save(orderVerification);
                    //记录分销商核销记录

                    if (orderItemMerchantRole == MerchantOrderMerchantRole.SUPPLIER) {
                        MerchantOrder distributorMerchantOrder = merchantOrderRepository.findByMarketOrderNumAndMerchantRole(marketOrderNum, MerchantOrderMerchantRole.DISTRIBUTOR);
                        Long distributorMerchantOrderId = distributorMerchantOrder.getId();
                        Long distributorMerchantOrderMerchantId = distributorMerchantOrder.getMerchantId();
                        List<MerchantOrderItem> itemList = merchantOrderItemRepository.findByMerchantOrderIdAndMerchantId(distributorMerchantOrderId, distributorMerchantOrderMerchantId);
                        String distributorMerchantOrderMerchantName = distributorMerchantOrder.getMerchantName();
                        MerchantOrderMerchantRole distributorMerchantOrderMerchantRole = distributorMerchantOrder.getMerchantRole();
                        MerchantOrderVerification verification = verificationHelper.merchantOrderVerificationSave(distributorMerchantOrder, itemList.get(0), orderItemBuyCount, null, customerDtoId, orderItemLogoUrl, distributorMerchantOrderMerchantName, OrderVerificationWay.SELF_CONFIRM, distributorMerchantOrderMerchantRole);
                        merchantOrderVerificationRepository.save(verification);
                    }
                    //产品事件记录
                    productEventHelper.productEventSave(merchantOrder, orderItem, orderItemBuyCount, ProductEventType.VERIFIED);
                    orderItem.setVerifyCount(orderItemBuyCount);
                    merchantOrderItemRepository.save(orderItem);
                }
                if (mallOrder.getGiftId() != null) {
                    fundService.giftPacketVerify(mallOrder, merchantOrder, null);
                } else {
                    fundService.productVerify(mallOrder, merchantOrder);
                }
            }
            // 订单事件记录
            orderEventHelper.saveOrderEvent(merchantOrder, OrderEventType.VERIFY_CONFIRM, customerDto.getNickName(), customerDtoId);
        };
        return doing.go(request, log);
    }
    public static void main(String[] args){
        /*TreeMap<Long,Object> rtMap =new TreeMap<Long,Object>(new CompareTo<Long>() {
            public int compare(Long o1, Long o2) {

                if(o1  > o2){
                    return  -1;
                }else{
                    return 0;
                }

            }

        });*/
        Map<String, String> m = new TreeMap<String, String>();
        m.put("2017-09-11 15:13:50", "d1");
        m.put("2017-09-11 15:12:14", "d0");
        m.put("2017-09-12 15:12:12", "ddd");
        m.put("2017-09-12 15:12:10", "ddd");
        m.put("2017-09-12 15:11:12", "ddd");
        for (Map.Entry<String, String> o : m.entrySet())
        {
            //System.out.println(o.getKey() + ", " + o.getValue());
        }


    }
}
